package com.fmdj.mis.api.controller;

import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.bean.BeanUtil;
import com.fmdj.common.util.CommonResult;
import com.fmdj.mis.api.controller.form.LoginForm;
import com.fmdj.mis.api.service.UserService;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("/user")
@Tag(name = "UserController", description = "用户Web接口")
public class UserController {

    @Resource
    private UserService userService;

    @PostMapping("/login")
    @Operation(summary = "登陆系统")
    public CommonResult login(@Valid @RequestBody LoginForm form) {
        Map param = BeanUtil.beanToMap(form);
        Integer userId = userService.login(param);
        CommonResult commonResult = CommonResult.ok().put("result", userId != null ? true : false);
        if (userId != null) {
            StpUtil.setLoginId(userId);
            Set<String> permissions = userService.selectUserPermissions(userId);
            String token = StpUtil.getTokenInfo().getTokenValue();
            commonResult.put("permissions", permissions).put("token", token);
        }
        return commonResult;
    }

    @GetMapping("/logout")
    @Operation(summary = "退出系统")
    public CommonResult logout() {
        StpUtil.logout();
        return CommonResult.ok();
    }
}

